class Popup {
    constructor(params) {
        this._init(params)
    }

    _init(params) {
        const _this = this
        _this.id = this._guid()
        _this.viewer = params.viewer//弹窗创建的viewer
        _this.geometry = params.geometry//弹窗挂载的位置
        _this.ctn = document.createElement('div')
        _this.ctn.classList.add('bx-popup-ctn')
        _this.ctn.setAttribute('id', this.id)
        _this.viewer.container.appendChild(this.ctn)
        _this.ctn.innerHTML = this._createHtml(params.title, params.content);
        _this._render();
        _this.eventListener = this.viewer.clock.onTick.addEventListener(() => {
            _this._render();
        })
        if(document.querySelector('.cesium-selection-wrapper-visible'))
            document.querySelector('.cesium-selection-wrapper-visible').style.opacity = 1
        document.getElementById(this.id + '_close').onclick = () => {
            this.close()
        }
    }

    _render() {
        const _this = this;
        const position = Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, this.geometry)
        _this.ctn.style.left = position.x- _this.ctn.offsetWidth / 2 + 'px';
        _this.ctn.style.top = position.y- _this.ctn.offsetHeight - 18 + 'px';
    }

    _createHtml(header = '',content = '') {
        return '<div class="bx-popup-header-ctn">'+
            header+
            '</div>'+
            '<div class="bx-popup-content-ctn" >'+
            '<div class="bx-popup-content" >'+
            content+
            '</div>'+
            '</div>'+
            '<div class="bx-popup-tip-container" >'+
            '<div class="bx-popup-tip" >'+
            '</div>'+
            '</div>'+
            '<a class="leaflet-popup-close-button" id="'+ this.id +'_close" >×</a>';
    }

    close() {
        const _this = this;
        _this.ctn.remove()
        _this.viewer.clock.onTick.removeEventListener( _this.eventListener );
        if(document.querySelector('.cesium-selection-wrapper-visible'))
            document.querySelector('.cesium-selection-wrapper-visible').style.opacity = 0
    }

    _guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            const r = Math.random() * 16 | 0,
                v = c === 'x' ? r : (r & 0x3 | 0x8)
            return v.toString(16);
        })
    }
}

export default Popup